package com.delianna.bwt;

import java.util.Date;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.delianna.bwt.helpers.Translator;
import com.delianna.bwt.models.BWT;
import com.delianna.bwt.models.Lane;
import com.delianna.bwt.models.Port;

/**
 * @author Delio Castillo (jangeador@gmail.com)
 * 
 */
public class PortDetailsActivity extends ListActivity {

	private static final String PREFS_NAME = "BWT_PREFS";
	private Port port;
	private String theme;
	private int requestCode;
	private int refreshTime;
	private long lastUpdate;
	private Translator trans;
	private static final String SP = " ";

	public void onCreate(Bundle savedInstanceState) {

		LoadPreferences();

		super.onCreate(savedInstanceState);
		setContentView(R.layout.port_detail);

		// Get the port id from the intent extras
		Bundle data = getIntent().getExtras();

		port = data.getParcelable("com.delianna.bwt.models.Port");

		updateDataOnScreen();

		updateIfNeeded();
	}

	public void updateDataOnScreen() {
		trans = new Translator(getBaseContext());

		// Set properties for UI
		TextView tvPortName = (TextView) findViewById(R.id.tvport_name);
		tvPortName.setText(port.getTitle());

		String reportedTime = getString(R.string.reported) + SP
				+ trans.TranslateByWord(port.getUpdateTime());
		String hours = getString(R.string.hours) + SP
				+ trans.TranslateByWord(port.hours);
		String date = getString(R.string.date) + SP + port.getDate();
		String status = null;
		if (port.port_status != null)
			status = getString(R.string.status) + SP
					+ trans.Translate(port.port_status);

		TextView tvreportedTime = (TextView) findViewById(R.id.tv_reportedtime);
		tvreportedTime.setText(reportedTime);

		TextView tvHours = (TextView) findViewById(R.id.tvhours);
		tvHours.setText(hours);

		TextView tvDate = (TextView) findViewById(R.id.tvdate);
		tvDate.setText(date);

		TextView tvStatus = (TextView) findViewById(R.id.tvportstatus);
		tvStatus.setText(status == null ? "" : status);

		setListAdapter(new LaneAdapter(this, R.layout.lane_row,
				port.getAllLanes()));

		setSettingString("LAST_PORT_VIEWED", port.port_number);
	}

	private void updateIfNeeded() {
		// Show last updated time
		long now = new Date().getTime();
		int minutesAgo = (int) ((now - this.lastUpdate) / 1000 / 60);
		Toast.makeText(
				this,
				getString(R.string.last_update_before_minutes) + " "
						+ minutesAgo + " "
						+ getString(R.string.last_update_after_minutes),
				Toast.LENGTH_LONG).show();

		if (refreshTime > 0 && (refreshTime - 1) < minutesAgo) {
			updateData();
		}
	}

	@Override
	protected void onResume() {
		if (port != null) {
			this.LoadPreferences();
			this.updateDataOnScreen();
		}
		super.onResume();
	}

	class LaneAdapter extends ArrayAdapter<Lane> {

		int resource;
		String response;
		Context context;

		// Initialize adapter
		public LaneAdapter(Context context, int resource, List<Lane> items) {
			super(context, resource, items);
			this.resource = resource;

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LinearLayout laneView;
			// Get the current alert object
			Lane la = getItem(position);

			// Inflate the view
			if (convertView == null) {
				laneView = new LinearLayout(getContext());
				String inflater = Context.LAYOUT_INFLATER_SERVICE;
				LayoutInflater vi;
				vi = (LayoutInflater) getContext().getSystemService(inflater);
				vi.inflate(resource, laneView, true);
			} else {
				laneView = (LinearLayout) convertView;
			}
			// Get the text boxes from the listitem.xml file
			TextView tvLaneType = (TextView) laneView
					.findViewById(R.id.lbllanetype);
			TextView tvLaneStatus = (TextView) laneView
					.findViewById(R.id.lblstatus);
			ImageView icon = (ImageView) laneView.findViewById(R.id.icon);

			// Assign the appropriate data from our alert object above
			String title = trans.Translate(la.getLaneClass()) + SP
					+ trans.Translate(la.getLaneType());

			// Subtitle for the lane
			String subtitle;
			StringBuilder sb = new StringBuilder();

			String status = la.getOperationalStatus();
			if (status.equalsIgnoreCase("no delay")) {
				sb.append(trans.Translate(status) + ".");
				sb.append(SP + trans.TranslateByWord(la.getLanesOpen()) + SP
						+ getString(R.string.lanes_open)+ ".");
			} else if (status.equalsIgnoreCase("lanes closed")) {
				sb.append(getString(R.string.lanes_closed));
			} else {
				sb.append(la.getDelayMinutes() == null ? "" : trans
						.TranslateByWord(la.getDelayMinutes()) + ".");
				sb.append(SP + trans.TranslateByWord(la.getLanesOpen()) + SP
						+ getString(R.string.lanes_open)+ ".");
			}
			subtitle = sb.toString();
			String laneClass = la.getLaneClass();
			if (subtitle == null)
				Log.v("Subtitle", "test");

			tvLaneType.setText(title);
			tvLaneStatus.setText(subtitle);

			if (laneClass != null) {
				if (la.getLaneClass().equals("Commercial")) {
					icon.setImageResource(R.drawable.truck_48);
				} else if (la.getLaneClass().equals("Passenger")) {
					icon.setImageResource(R.drawable.car_48);
				} else if (la.getLaneClass().equals("Pedestrian")) {
					icon.setImageResource(R.drawable.boot_48);
				}
			}
			return laneView;
		}

	}

	private void setSettingString(String key, String value) {
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(key, value);

		// Commit the edits!
		editor.commit();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("CheckStartActivity", "onActivityResult and resultCode = "
				+ resultCode);
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 1) {
			BWT bwt = data.getExtras().getParcelable(
					"com.delianna.bwt.models.BWT");
			port = bwt.getPort(port.port_number);
			onResume();

			Toast.makeText(this, R.string.update_success, Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, R.string.update_failure, Toast.LENGTH_LONG).show();
		}
	}

	private void LoadPreferences() {
		// Load Default Preferences or set preferences
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		theme = prefs.getString("themePref", "dark");
		refreshTime = Integer.parseInt(prefs.getString("refreshPref", "30"));

		if (theme.equals("lite")) {
			setTheme(R.style.Lite);
		} else if (theme.equals("dark")) {
			setTheme(R.style.Dark);
		}
		this.lastUpdate = prefs.getLong("lastUpdate", 0);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.portdetail_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.refresh:
			updateData();
			break;
		case R.id.settings:

			// Call Settings
			Intent settingsActivity = new Intent(getBaseContext(),
					SettingsActivity.class);
			startActivity(settingsActivity);

			break;
		}
		return true;
	}

	private void updateData() {
		Intent intent = new Intent(PortDetailsActivity.this,
				RefreshDataActivity.class);
		startActivityForResult(intent, requestCode);
	}
}
